package com.lyl.momanapp.util.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.os.Environment;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.ImageView;

import com.lyl.momanapp.bean.CJBean;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

/**
 * Created by shangzhaohui on 16/3/27.
 */
public class ClipImageView extends ImageView {
    public enum Style {
        RECTANGLE,
        POLYGON
    }

    static CJBean cjBean = new CJBean();
    private Context mContext;

    private Style mStyle = Style.RECTANGLE;

    ArrayList<Point> mPointList = new ArrayList<>();


    private Paint mPaint;

    public ClipImageView(Context context) {
        super(context);
        mContext = context;
        init();
    }

    public ClipImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        init();
    }

    public ClipImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        init();
    }

    private void init() {
        mPaint = new Paint();
        mPaint.setColor(Color.RED);
    }

    boolean need = false;

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (mStyle == Style.RECTANGLE) {
            mPaint.setStyle(Paint.Style.STROKE);
            float left = cjBean.startX > cjBean.endX ? cjBean.endX : cjBean.startX;
            float top = cjBean.startY > cjBean.endY ? cjBean.endY : cjBean.startY;
            float right = cjBean.startX > cjBean.endX ? cjBean.startX : cjBean.endX;
            float bottom = cjBean.startY > cjBean.endY ? cjBean.startY : cjBean.endY;

            Log.e("onDraw", "left:" + left + "top:" + top + "right:" + right + "bottom" + bottom);

            canvas.drawRect(left, top, right, bottom, mPaint);
        } else {
            canvas.drawPath(getPath(mPointList), mPaint);
        }

    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {

        int action = event.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                if (mStyle == Style.RECTANGLE) {
                    cjBean.startX = event.getX() < 0 ? 0 : event.getX();
                    cjBean.startY = event.getY() < 0 ? 0 : event.getY();
                } else {
                    Point p = new Point((int) event.getX(), (int) event.getY());
                    mPointList.add(p);
                    invalidate();
                }

                break;
            case MotionEvent.ACTION_MOVE:
                if (mStyle == Style.RECTANGLE) {
                    cjBean.endX = event.getX() > getWidth() ? getWidth() : event.getX();
                    cjBean.endY = event.getY() > getHeight() ? getHeight() : event.getY();
                    invalidate();
                }

                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                break;
        }

        return true;
    }

    @Override
    public void setBackgroundResource(int resid) {
        setBackground(null);
        setImageBitmap(null);
        super.setBackgroundResource(resid);

        orginalBitmap = BitmapFactory.decodeResource(mContext.getResources(),resid);
        reset();
    }

    public void setBitmap() throws IOException {
        if (mStyle == Style.RECTANGLE) {
            float left = cjBean.startX > cjBean.endX ? cjBean.endX : cjBean.startX;
            float top = cjBean.startY > cjBean.endY ? cjBean.endY : cjBean.startY;
            if (left <= 0 || top <= 0) {
                return;
            }
            Bitmap bitmap = getBitmap();
            setImageBitmap(null);
            setBackground(null);
            orginalBitmap = Bitmap.createBitmap(bitmap, (int) left, (int) top, (int) Math.abs(cjBean.endX - cjBean.startX), (int)
                    Math.abs(cjBean.endY - cjBean.startY));
            setImageBitmap(orginalBitmap);

            setDrawingCacheEnabled(false);
            reset();
        } else {
            float minX = 10000, minY = 10000, maxX = 0, maxY = 0;
            for (Point p : mPointList) {
                if (minX > p.x) {
                    minX = p.x;
                }
                if (minY > p.y) {
                    minY = p.y;
                }
                if (maxX < p.x) {
                    maxX = p.x;
                }
                if (maxY < p.y) {
                    maxY = p.y;
                }
            }
            ArrayList<Point> list = new ArrayList<>();
            for (Point p : mPointList
                    ) {
                Point point = new Point();
                point.x = (int) (p.x - minX);
                point.y = (int) (p.y - minY);
                list.add(point);
            }

            Bitmap bitmap = getBitmap();

            width = (int) (maxX - minX) > orginalBitmap.getWidth() ? orginalBitmap.getWidth() : (int) (maxX - minX);
            heigh = (int) (maxY - minY) > orginalBitmap.getHeight() ? orginalBitmap.getHeight() : (int) (maxY - minY);
            if (width <= 0 || heigh <= 0) {
                return;
            }
            orginalBitmap = Bitmap.createBitmap(bitmap, (int) minX, (int) minY, width, heigh);


            setImageBitmap(null);
            setBackground(null);
            mPointList.clear();

            Canvas canvas = new Canvas(orginalBitmap);

            canvas.drawARGB(0, 0, 0, 0);
            Paint p = new Paint();
            p.setColor(Color.WHITE);
            p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
            Path path = getPath(list);
            path.setFillType(Path.FillType.INVERSE_WINDING);
            canvas.drawPath(path, p);
            saveFile(orginalBitmap, "asdasd1.jpg");
            setDrawingCacheEnabled(false);
            reset();
        }

    }

    public void saveFile(Bitmap bm, String fileName) throws IOException {
        String path = Environment.getExternalStorageDirectory() + File.separator;
        File dirFile = new File(path);
        if (!dirFile.exists()) {
            dirFile.mkdir();
        }
        File myCaptureFile = new File(path + fileName);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();
    }

    int width;
    int heigh;

    Bitmap orginalBitmap;

    public Bitmap getBitmap() {

        return orginalBitmap;
    }

    public void changeStyle() {
        if (mStyle == Style.RECTANGLE) {
            mStyle = Style.POLYGON;
        } else {
            mStyle = Style.RECTANGLE;
        }
    }

    public String getStyleStr() {
        if (mStyle == Style.POLYGON) {
            return "多边形";
        }
        return "矩形";
    }

    private void reset() {
        cjBean.startX = 0;
        cjBean.startY = 0;
        cjBean.endX = 0;
        cjBean.endY = 0;
        mPointList.clear();
    }

    private Path getPath(ArrayList<Point> pointList) {
        Path path = new Path();
        boolean first = true;
        for (Point p : pointList) {
            if (first) {
                path.moveTo(p.x, p.y);
                first = false;
            } else {
                path.lineTo(p.x, p.y);
            }
        }
        path.close();
        return path;
    }

}
